package dao

import (
	"admin_srv/basic/config"
	admin "admin_srv/basic/proto"
	"admin_srv/handler/model"
	"fmt"
	"time"
)

// 获取即将到期的会员列表
func GetExpiringVips(in *admin.GetExpiringVipsReq) ([]*admin.ExpiringVip, string, error) {
	//校验参数
	if in.Days < 0 || in.Days > 30 {
		return nil, "", fmt.Errorf("天数必须在0-30之间")
	}

	var expiringVip model.ExpiringVipDetail
	details, err := expiringVip.GetExpiringVips(int(in.Days))
	if err != nil {
		return nil, "", fmt.Errorf("获取到期会员列表失败")
	}

	//如果没有到期会员提示
	if len(details) == 0 {
		var message string
		if in.Days == 0 {
			message = "今天没有到期会员"
		} else {
			message = fmt.Sprintf("未来%d天内没有到期的会员", in.Days)
		}
		return []*admin.ExpiringVip{}, message, nil
	}

	var result []*admin.ExpiringVip
	for _, detail := range details {
		daysLeft := int64(detail.EndTime.Sub(time.Now()).Hours() / 24)
		if daysLeft < 0 {
			daysLeft = 0
		}
		result = append(result, &admin.ExpiringVip{
			UserId:   int64(detail.UserId),
			Phone:    detail.Phone,
			Nickname: detail.Nickname,
			PlanName: detail.PlanName,
			EndTime:  detail.EndTime.Format(time.DateTime),
			DaysLeft: daysLeft,
		})
	}
	message := fmt.Sprintf("共找到%d个即将到期的会员", len(result))
	return result, message, nil

}

// 发送会员到期提醒
func SendVipExpireReminders(in *admin.SendVipExpireRemindersReq) (*admin.SendVipExpireRemindersResp, error) {
	//参数验证
	if in.DaysBefore < 0 || in.DaysBefore > 30 {
		return nil, fmt.Errorf("天数参数必须在0-30之间")
	}
	//获取即到期的会员列表
	var expiringVip model.ExpiringVipDetail
	details, err := expiringVip.GetExpiringVips(int(in.DaysBefore))
	if err != nil {
		return nil, fmt.Errorf("获取到期会员列表失败")
	}

	//如果没有数据
	if len(details) == 0 {
		var message string
		if in.DaysBefore == 0 {
			message = "今天没有到期的会员"
		} else {
			message = fmt.Sprintf("未来%d天内没有到期的会员", in.DaysBefore)
		}
		return &admin.SendVipExpireRemindersResp{
			Success:      true,
			Message:      message,
			TotalCount:   0,
			SuccessCount: 0,
			FailCount:    0,
		}, nil
	}
	//发送短信
	var successCount, failCount int64
	for _, detail := range details {
		success, err2 := sendSingleReminder(detail, in.DaysBefore)
		if success {
			successCount++
		} else {
			failCount++
			fmt.Printf("发送失败 user_id=%d: %v\n", detail.UserId, err2)
		}
	}
	message := fmt.Sprintf("发送完成：成功%d个，失败%d个", successCount, failCount)
	return &admin.SendVipExpireRemindersResp{
		Success:      true,
		Message:      message,
		TotalCount:   int64(len(details)),
		SuccessCount: successCount,
		FailCount:    failCount,
	}, nil
}

// 发送单个会员提醒
func sendSingleReminder(detail model.ExpiringVipDetail, daysBefore int64) (bool, error) {
	// 生成短信内容
	var message string
	if daysBefore > 0 {
		message = fmt.Sprintf("亲爱的%s，您的%s会员将在%d天后到期。为了不影响您的会员权益，请及时续费哦！",
			detail.Nickname, detail.PlanName, daysBefore)
	} else {
		message = fmt.Sprintf("亲爱的%s，您的%s会员今天到期。立即续费可继续享受会员特权！",
			detail.Nickname, detail.PlanName)
	}

	//使用短信内容作为参数
	redisKey := fmt.Sprintf("VipReminder:%d:%d", detail.UserId, daysBefore)

	//存储短信内容到redis,设置过期时间为1天
	err := config.Rdb.Set(config.Ctx, redisKey, message, 7*24*time.Hour).Err()
	if err != nil {
		fmt.Printf("存储短信内容到redis失败", err.Error())
	}
	// 使用你封装好的pkg发送短信
	//sms, err := pkg.SendSms(config.SignName, config.TemplateCode, detail.Phone, message)
	//if err != nil {
	//	return false, fmt.Errorf("发送会员到期提醒短信失败：%s", err.Error())
	//}
	//
	//if *sms.Body.Code != "OK" {
	//	return false, fmt.Errorf("发送会员到期提醒短信失败：%s", *sms.Body.Message)
	//}

	// 记录发送日志（可选）
	fmt.Printf("发送成功: %s -> %s\n", detail.Phone, message)

	return true, nil
}
